<?php
include_once __DIR__ . '/BaseShell.php';
while (true) {
    $data = Lib_Redis_List::LPop("RECORD_FILE_KEY");
    if (empty($data)) {//目前需要修复中的数据
        sleep(5);
        continue;
    }
    // $data = '{"mainUniqueId":"medias_2-1632457923.6768","case_id":"40","record_id":"2"}';
    $data = json_decode($data,true);
    if(empty($data['case_id']) || empty($data['record_id'])){
        continue;
    }
    $downUrl = '';
    //一切正常 connect_status传了，并且没有接通
    if(!empty($data['connect_status']) && !in_array($data['connect_status'],['dealing','voicemail'])){
        Func_Log::write('recode_file', "NOT CALL" ,json_encode($data));
        continue;
    }
    //如果前段传downFile用前段传的
    if($data['downFile'] && $data['connect_status']){
        $downUrl = $data['downFile'];
    }else{//异常没传
        //再判断前段是否传CallSheetID
        if(!empty($data['CallSheetID'])){
            $downUrl = Lib_Redis_String::get($data['CallSheetID']);
            if(empty($downUrl)){
                for ($i=0;$i<5;$i++){
                    $downUrl = Lib_Redis_String::get($data['CallSheetID']);
                    if($downUrl){
                        break;
                    }
                    sleep(2);
                }
            }
        }else{//没传CallSheetID
            $call_record = Lib_Redis_Hash::hGetAll($data['case_id']);
            if(empty($call_record)){
                for ($i=0;$i<5;$i++){
                    $call_record = Lib_Redis_Hash::hGetAll($data['case_id']);
                    if($call_record){
                        break;
                    }
                    sleep(2);
                }
            }
            if($call_record){
                $data['CallSheetID'] = key($call_record);
                $downUrl = Lib_Redis_String::get($data['CallSheetID']);
            }
        }
    }
    if(empty($call_record)){
        $call_record = Lib_Redis_Hash::hGetAll($data['case_id']);
    }
    //删除hash
    if($call_record && count($call_record) == 1){
        Lib_Redis_Hash::del($data['case_id']);
    }elseif($call_record){
        Lib_Redis_Hash::hDel($data['case_id'],key($call_record));
    }
    if(empty($downUrl)){
        Func_Log::write('recode_file', "downUrl EMPTY" ,json_encode($data));
        continue;
    }
    if($downUrl == 'emptyFile'){
        Func_Log::write('recode_file', "downUrl EMPTY NOT CALL" ,json_encode($data));
        continue;
    }

    $down_time =  empty($data['down_time']) ?  0 : $data['down_time'];
    //下载录音等待1分钟
    if(($down_time - time()) > 0) {
        sleep($down_time - time());
    }
    $CallSheetID = empty($data['CallSheetID']) ?  uniqid() : $data['CallSheetID'];
    $up_file_name = downloadFile($downUrl,$CallSheetID);

    //修改
    if($up_file_name){
        $res = Module_Mediate_CaseMediateLog::getInstance()->update(['spare_file_name'=>$up_file_name],$data['case_id'],$data['record_id']);
        if(!$res){
            //记录日志
            Func_Log::write('recode_file', "update_filename_fail,res=",$res.",file_name=".$savefile,',case_id='.$data['case_id'].',record_id='.$data['record_id']);
            continue;
        }
        Func_Log::write('recode_file', "update_filename_success","file_name=".$up_file_name.'data='.json_encode($data));
    }

}

function downloadFile($downUrl,$CallSheetID){
    Func_Log::write('recode_file', "downloadFile {$CallSheetID}",$downUrl);
    //初始化文件
    $save_date = date('Y-m-d').'/';
    $savePath = LIBRARY_DIR."/../evidence/spareRecordfile/".$save_date;
    if(!file_exists($savePath)){
        if(!@mkdir($savePath,0777,true)){
            Func_Log::write('recode_file', "Can not make dir",$savePath);
            return '';
        }
    }
    //录音已经下载
    if(file_exists($savePath.$CallSheetID.'.mp3')){
        return $save_date.$CallSheetID.'.mp3';
    }
    sleep(1);
    if($downUrl){
        $header_array = get_headers($downUrl, true);
        $size = $header_array['Content-Length'];
        $type = $header_array['Content-Type'];
        if (!$size || strstr($type,'audio') === false || $size < 500){
            $num = Lib_Redis_String::get("DOWNLOADFILE1" . $CallSheetID);
            $num = $num ? $num : 1;
            if($num > 5){
                return '';
            }
            sleep(8);
            Lib_Redis_String::setex("DOWNLOADFILE1" . $CallSheetID,1800,$num+1);
            return downloadFile($downUrl,$CallSheetID);
        }
    }else{
        Func_Log::write('recode_file', "downloadFile empty downUrl","CallSheetID = ".$CallSheetID );
        return '';
    }
    sleep(1);
    //下载文件
    $url = $downUrl;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $fp = fopen($savePath.$CallSheetID.'.mp3', 'w');
    $result = fwrite($fp, $rawdata);
    fclose($fp);
    if($result && file_exists($savePath.$CallSheetID.'.mp3')){
        return $save_date.$CallSheetID.'.mp3';
    }
    if (strlen($rawdata) < 100){
        Func_Log::write('recode_file', "downloadFile fail","CallSheetID = ".$CallSheetID ."res = ",var_export($result,1).$rawdata);
    }
    Func_Log::write('recode_file', "downloadFile fail","CallSheetID = ".$CallSheetID ."res = ",var_export($result,1));
    $num = Lib_Redis_String::get("DOWNLOADFILE1" . $CallSheetID);
    $num = $num ? $num : 1;
    if($num > 5){
        return '';
    }
    Lib_Redis_String::setex("DOWNLOADFILE1" . $CallSheetID,1800,$num+1);
    return downloadFile($downUrl,$CallSheetID);
}